package org.springframework.samples.petclinic.web

import java.util.Collection

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.InitBinder
import org.springframework.web.bind.WebDataBinder

import org.springframework.samples.petclinic.Clinic
import org.springframework.samples.petclinic.Owner

@Controller
@RequestMapping(Array("/findOwners.do"))
class FindOwnersForm {
  
  private var clinic:Clinic = null

  @Autowired 
  def setClinic(clinic:Clinic) = {
    this.clinic = clinic
  }
  
  @InitBinder
  def setAllowedFields(dataBinder:WebDataBinder) = {
    dataBinder.setDisallowedFields(Array("id"))
  }
   
  @RequestMapping {val method = Array(RequestMethod.GET)}
  def setupForm(model:Model):String = {
    model.addAttribute("owner", new Owner())
    return "findOwners"
  }
  
  @RequestMapping {val method = Array(RequestMethod.POST)}
  def processSubmit(owner:Owner, result:BindingResult, model:Model):String = {
    val results = this.clinic.findOwners(owner.lastName)
    if (results.size() < 1) {
      result.rejectValue("lastName", "notFound", "not found")
      return "findOwners"
    }
    if (results.size() > 1) {
      model.addAttribute("selections", results)
      return "owners"
    } else {
      //In the java variant the parameter owner is reassigned.
      //Not sure how to do this in scala (even though it's bad practise)
      val owner2 = results.iterator().next()
      return "redirect:owner.do?ownerId=" + owner2.id
    }
  }
  
}
